package com.netty.heartbeat;

import java.net.InetAddress;
import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.Sigar;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;

public class ClientHeartBeatHandler extends ChannelHandlerAdapter{

	private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
	private ScheduledFuture<?> heartBeat;
	//主动向服务器发送认证信息
	private InetAddress addr;
	private static final String SUCCESS_KEY = "auth_success";
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		addr = InetAddress.getLocalHost();
		String ip = addr.getHostAddress();
		String key = "12345";
		String auth = ip +","+ key;
		ctx.writeAndFlush(auth);
	}
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		try {
			if(msg instanceof String){
				String ret = (String) msg;
				if(SUCCESS_KEY.equals(ret)){
					//验证成功
					this.heartBeat = this.scheduler.scheduleWithFixedDelay(new HeartBeatTask(ctx), 0, 2, TimeUnit.SECONDS);
					System.out.println(msg);
				}else{
					System.out.println(msg);
				}
			}
		} finally {
			ReferenceCountUtil.release(msg);
		}
	}
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		if(heartBeat != null){
			heartBeat.cancel(true);
			heartBeat = null;
		}
		ctx.fireExceptionCaught(cause);
	}
	
	
	private class HeartBeatTask implements Runnable {
		
		private final ChannelHandlerContext ctx;
		
		public HeartBeatTask(ChannelHandlerContext ctx) {
			this.ctx = ctx;
		}
		@Override
		public void run() {
			try {
				RequestInfo info = new RequestInfo();
				//IP
				info.setIp(addr.getHostAddress());
				//Sigar 使用方式：将sigar-bin\lib目录了下选择相应系统的sigar-xxx-xxx文件
				//拷贝到Java_home\bin目录下
				Sigar sigar = new Sigar();
				CpuPerc perc = sigar.getCpuPerc();
				HashMap<String, Object> cpuPercMap = new HashMap<>();
				cpuPercMap.put("combined", perc.getCombined());
				cpuPercMap.put("user", perc.getUser());
				cpuPercMap.put("sys", perc.getSys());
				cpuPercMap.put("wait", perc.getWait());
				cpuPercMap.put("idle", perc.getIdle());
				//内存相关
				Mem mem = sigar.getMem();
				HashMap<String , Object> memoryMap = new HashMap<>();
				memoryMap.put("total", mem.getTotal() / 1024L);
				memoryMap.put("used", mem.getUsed() / 1024L);
				memoryMap.put("free", mem.getFree() / 1024L);
				info.setCpuPercMap(cpuPercMap);
				info.setMemoryMap(memoryMap);
				ctx.writeAndFlush(info);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
	
}
